<template>
    <div class="collapse-panel">
        <slot></slot>
    </div>
</template>

<script setup lang="ts">
import { useSlots, ref, onMounted, provide } from "vue";

const slots = useSlots();
const props = defineProps({
    modelValue: {
        type: [String, Array, Number],
    }, // 数据绑定
    accordion: {
        type: Boolean,
    }, // 是否开启手风琴模式，默认不开启
});
const emits = defineEmits(["update:modelValue", "change"]);

const activeNames = ref([]);

onMounted(() => {
    setValueLists();
});

// 初始化设置激活项
const setValueLists = () => {
    if (!Array.isArray(props.modelValue)) {
        activeNames["value"] = [props.modelValue];
    } else {
        activeNames["value"] = props.modelValue;
    }
};
// 点击每项处理函数
const toggle = (name) => {
    if (activeNames["value"].includes(name)) {
        // 收起时
        activeNames["value"] = activeNames["value"].filter((item) => item != name);
    } else {
        // 展开时
        if (props.accordion) {
            activeNames["value"] = [name];
        } else {
            activeNames["value"].push(name);
        }
    }
    emits("update:modelValue", activeNames["value"]);
    emits("change", activeNames["value"]);
};

// 提供父组件指定方法
provide("toggle", toggle);
provide("activeNames", activeNames);
</script>

<style scoped></style>
